package com.example.a828502.sfdialtestdemo;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.a828502.Utils.GsonUtils;
import com.example.a828502.Utils.InputDialog;
import com.example.a828502.httpHelper.GetTaskListHelper;
import com.example.a828502.httpHelper.HttpConstans;
import com.example.a828502.httpHelper.HttpUtils;
import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 一个Fragment整合所有的功能
 * Created by 828502 on 2016/5/17.
 */
public class PSTNCallbackFragment extends Fragment {

    private Context mContext;
    private ListView mListViewContent;
    private EditText mTxtURL,mTxtPort;
    private Button mBtnSettings;
    private TextView mTxtOK,mTxtTip;

    private TextView mTxtCallback;
    private TextView mTxtCall;
    private MyListAdapter mMyListAdapter;
    private List<ListItem> mList = new ArrayList<ListItem>();
    private InputDialog mSettingDialog;
    private int white = 0xFFFFFFFF;
    private int gray = 0xFF7597B3;
    private int blue =0xFF0AB2FB;

    private final OkHttpClient client = new OkHttpClient();

    String requestIP = "";
    String requestPort = "";
    String dialType = "";
    String dialPhonrNumber = "";//直拨号码

    private final int GETKLISTSUCCESS = 1;
    private final int FAILURE = 0;
    private final int ERRORCODE = 2;
    private final int DIALSUCCESS = 3;
    private final int DELIVEREDSUCCESS = 4;
    private final int NODATA = 5;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
//        System.setProperty("http.keepAlive", "false");
        View view = inflater.inflate(R.layout.fg_pstn, container,false);
        mContext = this.getActivity();

        mTxtTip = (TextView)view.findViewById(R.id.textTip);
        mListViewContent = (ListView) view.findViewById(R.id.listViewContent);
        mTxtCallback = (TextView) view.findViewById(R.id.textCallback);
        mBtnSettings = (Button)view.findViewById(R.id.btnSettings);
        mTxtCall = (TextView) view.findViewById(R.id.textCall);
        //默认回拨请求
//        mTxtCallback.setTextColor(blue);
//        mTxtCallback.setBackgroundColor(gray);
//        dialType = "1";//设置拨号方式
//        doGetTaskListRequest();//请求任务列表
        mTxtCallback.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                clearChioce();
                dialType = "1";//设置拨号方式
                mTxtCallback.setTextColor(blue);
                mTxtCallback.setBackgroundColor(gray);
                mTxtTip.setText("PSTN回拨");
                doGetTaskListRequest();//请求任务列表
            }
        });
        mTxtCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearChioce();
                dialType = "0";//设置拨号方式
                mTxtCall.setTextColor(blue);
                mTxtCall.setBackgroundColor(gray);
                mTxtTip.setText("PSTN直拨");
                doGetTaskListRequest();//请求任务列表
            }
        });
        mBtnSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSettingsDialog();
            }
        });
        return view;
    }

    /**
     * 设置网络连接参数
     */
    private void showSettingsDialog() {
        mSettingDialog = new InputDialog(mContext);
        mSettingDialog.setPositiveButton("确定", new View.OnClickListener() {
            public void onClick(View v) {
                requestIP = mSettingDialog.getIP().trim();//获取连接IP
                requestPort = mSettingDialog.getPort().trim();//获取连接Port
                mSettingDialog.dismiss();
            }
        });

        mSettingDialog.show();
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GETKLISTSUCCESS:

                    if (null!= mList && mList.size()>0){
                        Toast.makeText(mContext, "获取数据成功", Toast.LENGTH_SHORT)
                                .show();
                    }else {
                        Toast.makeText(mContext, "暂无数据", Toast.LENGTH_SHORT)
                                .show();
                    }

                    mMyListAdapter = new MyListAdapter(mContext, mList);
                    mListViewContent.setAdapter(mMyListAdapter);
                    setListener();

                    break;

                case FAILURE:
                    Toast.makeText(mContext, "获取数据失败", Toast.LENGTH_SHORT)
                            .show();
                    break;

                case ERRORCODE:
                    Toast.makeText(mContext, "获取的CODE码不为200！",
                            Toast.LENGTH_SHORT).show();
                    break;
                case DIALSUCCESS:


                    if(null!=dialPhonrNumber &&!("".equals(dialPhonrNumber))){
                        Uri uri = Uri.parse("tel:" + dialPhonrNumber);
                        Intent intent = new Intent(Intent.ACTION_DIAL, uri);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        mContext.startActivity(intent);
                    }

                    Toast.makeText(mContext, "拨号成功", Toast.LENGTH_SHORT)
                            .show();
                    break;
                case DELIVEREDSUCCESS:
                    doGetTaskListRequest();//请求任务列表
                    Toast.makeText(mContext, "妥投成功", Toast.LENGTH_SHORT)
                            .show();
                    break;
                case NODATA:
                    mMyListAdapter = new MyListAdapter(mContext, mList);
                    mListViewContent.setAdapter(mMyListAdapter);
                    setListener();
                    Toast.makeText(mContext, "暂无数据", Toast.LENGTH_SHORT)
                            .show();
                    break;
                default:
                    break;
            }
        }
    };


    //定义一个重置所有选项的方法
    public void clearChioce()
    {
        mTxtCallback.setBackgroundColor(white);
        mTxtCallback.setTextColor(gray);
        mTxtCall.setBackgroundColor(white);
        mTxtCall.setTextColor(gray);
    }
    /**
     * 设置监听
     */
    private void setListener() {
        /**
         * 完成按钮监听
         */
        mMyListAdapter.setComBtnOnClickListener(new MyListAdapter.OnComBtnOnClickListener() {

            @Override
            public void OnComBtnOnClickListener(String waybillNO, int position, MyListAdapter.ViewContent viewHolder) {
                doCompleteRequest(waybillNO);
            }
        });

        /**
         * 拨号按钮监听
         */
        mMyListAdapter.setDialBtnOnClickListener(new MyListAdapter.OnDialBtnOnClickListener() {

            @Override
            public void OnDialBtnOnClickListener(String waybillNO, int position, MyListAdapter.ViewContent viewHolder) {
                doDialeRequest(waybillNO);
            }
        });
    }

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    /**
     * 完成 接口请求
     * @param waybillNo
     */
    public void doCompleteRequest(String waybillNo){
        if ("".equals(requestIP) ||"".equals(requestPort)){
            Toast.makeText(mContext, "请设置网络连接地址", Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        JSONObject jsonParam = new JSONObject();//定义json对象
        try {
            jsonParam.put("waybillNo", waybillNo);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String path = "http://"+requestIP+":"+requestPort+ HttpConstans.Method.DO_COMPLETE; //组合请求地址


        RequestBody body = RequestBody.create(JSON, String.valueOf(jsonParam));
        Request request = new Request.Builder()
                .url(path)
                .post(body)
                .build();

        Call call = client.newCall(request);
        // 开启异步线程访问网络
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Request request, IOException e) {
                Message msg = new Message();
                msg.what = FAILURE;
                handler.sendMessage(msg);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                results = response.body().string();
                Message msg = new Message();
                msg.what = DELIVEREDSUCCESS;
                handler.sendMessage(msg);


                Log.i("_+_+_+_+", results);

            }
        });


    }

    /**
     * 发送回拨请求
     * @param waybillNO
     */
    public void doDialeRequest(String waybillNO){
        if ("".equals(requestIP) ||"".equals(requestPort)){
            Toast.makeText(mContext, "请设置网络连接地址", Toast.LENGTH_SHORT)
                    .show();
            return;
        }

        JSONObject jsonParam = new JSONObject();//定义json对象
        try {
            jsonParam.put("waybillNo", waybillNO);
            jsonParam.put("Type", dialType);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String path = "http://"+requestIP+":"+requestPort+ HttpConstans.Method.DO_DIAL; //组合请求地址
        RequestBody body = RequestBody.create(JSON, String.valueOf(jsonParam));
        Request request = new Request.Builder()
                .url(path)
                .post(body)
                .build();

        Call call = client.newCall(request);
        // 开启异步线程访问网络
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Request request, IOException e) {
                Message msg = new Message();
                msg.what = FAILURE;
                handler.sendMessage(msg);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                results = response.body().string();
                Message msg = new Message();
                msg.what = DIALSUCCESS;
                handler.sendMessage(msg);

                JSONObject object = null;
                try {
                    object = new JSONObject(results);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                dialPhonrNumber = object.optString("obj");
                Log.i("_+_+_+_+", dialPhonrNumber);

            }
        });


    }


    /**
     * 获取任务列表
     */

    private String results = "";
    public void doGetTaskListRequest(){
        if ("".equals(requestIP) ||"".equals(requestPort)){
            Toast.makeText(mContext, "请设置网络连接地址", Toast.LENGTH_SHORT)
                    .show();
            return;
        }

        String path = "http://"+requestIP+":"+requestPort+ HttpConstans.Method.GET_TASK_LIST; //组合请求地址

        Request request = new Request.Builder()
                .url(path)
                .build();
        Call call = client.newCall(request);


        // 开启异步线程访问网络
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Request request, IOException e) {
                Message msg = new Message();
                msg.what = FAILURE;
                handler.sendMessage(msg);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                results = response.body().string();
                JSONArray ObjectInfo = null;
                JSONObject object = null;
                try {
                    object = new JSONObject(results);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (null!=object) {
                    ObjectInfo = object.optJSONArray("obj");
                }
                mList =  GsonUtils.json2Array(ObjectInfo.toString(),ListItem.class);


                Message msg = new Message();
                msg.obj = mList;
                if (null!= mList && mList.size()>0){
                    msg.what = GETKLISTSUCCESS;
                }else {
                    msg.what = NODATA;
                }
                handler.sendMessage(msg);

            }
        });
    }

}
